<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-15px">
      <el-form-item label="商户ID" prop="id">
        <el-input
          v-model="queryParams.id"
          class="!w-240px"
          clearable
          placeholder="请输商户名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商户名称" prop="name">
        <el-input
          v-model="queryParams.name"
          class="!w-240px"
          clearable
          placeholder="请输商户名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          class="!w-220px"
          end-placeholder="结束日期"
          start-placeholder="开始日期"
          type="datetimerange"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list">
      <el-table-column label="ID" min-width="80" prop="id" />
      <el-table-column label="商户名称" min-width="220" prop="name" align="left">
        <template #default="scope">
          <div class="flex">
            <div>
              <el-image
                :preview-teleported="true"
                :src="scope.row.avatar"
                class="w-[48px]! h-[48px]! m-r-10px rounded-4px align-middle"
              />
            </div>

            <el-text>{{ scope.row.name }}</el-text>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="商户类型" min-width="100" prop="tenantType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.TENANT_IDENTITY" :value="scope.row.tenantType" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="开启状态" min-width="100" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        :formatter="dateFormatter"
        align="center"
        label="创建时间"
        prop="createTime"
        width="180"
      />
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <el-button link type="primary" @click="switchTenant(scope.row.id)"> 切换 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
</template>
<script lang="ts" name="DeliveryPickUpStore" setup>
import * as UserApi from '@/api/system/user'
import * as LoginApi from '@/api/login'
import { DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { propTypes } from '@/utils/propTypes'
import { ElLoading } from 'element-plus'
import { deleteUserCache } from '@/hooks/web/useCache'
const tagsViewStore = useTagsViewStore()
/** 门店会员信息 */
import { useShopUserStoreWithOut } from '@/store/modules/shop/user'
const shopUserStore = useShopUserStoreWithOut()
/** 门店会员列表查询 */
import { useShopMemberListStoreWithOut } from '@/store/modules/shop/memberList'
const shopMemberListStore = useShopMemberListStoreWithOut()
// 用来处理是组件 还是页面
defineProps({
  type: propTypes.string.def('page'),
  // 多选模式
  multiple: propTypes.bool.def(false)
})
const emit = defineEmits(['success'])

const total = ref(0) // 列表的总页数
const loading = ref(true) // 列表的加载中
const list = ref<any[]>([{}]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  status: undefined,
  name: undefined,
  id: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单

/** 切换 */
const loginLoading = ref()
import * as authUtil from '@/utils/auth'
const { replace } = useRouter()
import { useUserStoreWithOut } from '@/store/modules/user'
import { useTagsViewStore } from '@/store/modules/tagsView'

const userStore = useUserStoreWithOut()

const switchTenant = async (id?: number) => {
  try {
    const res = await LoginApi.switchTenant({ tenantId: id })
    if (!res) {
      return
    }
    emit('success')
    loginLoading.value = ElLoading.service({
      lock: true,
      text: '正在切换账号中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    await userStore.resetState()
    await shopUserStore.resetState()
    await shopMemberListStore.resetState()

    deleteUserCache() // 删除用户缓存
    closeAllTags()
    authUtil.setToken(res)
    authUtil.setTenantType(res.tenantType)
    authUtil.setTenantId(res.tenantId)
  } finally {
    refreshSelectedTag()
    loginLoading.value.close()
  }
}
// 关闭全部
const closeAllTags = () => {
  tagsViewStore.delAllViews()
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await UserApi.getAccountBindTenantList(queryParams)
    list.value = data
    // total.value = data
  } finally {
    loading.value = false
  }
}
// 重新加载
const refreshSelectedTag = async () => {
  replace({
    path: '/redirect' + '/index'
  })
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
